package com.spark.lola.support.warehouse.service;

import com.alibaba.fastjson.JSON;
import com.spark.lola.constant.GatherType;
import com.spark.lola.entity.warehouse.GatherLog;
import com.spark.lola.support.common.util.HttpUtil;
import com.spark.lola.support.warehouse.configuration.FztApiProperties;
import com.spark.lola.dto.warehouse.*;
import com.spark.lola.support.warehouse.constant.WarehouseCache;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * 废纸通 采集业务
 * @Author: DengYeJun
 * @Date: 2020/6/10 10:29
 */
@Service
public class FeiZhiTongServiceImpl {
    private static final Logger logger = LoggerFactory.getLogger(FeiZhiTongServiceImpl.class);

    private FztApiProperties apiProperties;
    @Autowired
    private KafkaTemplate kafkaTemplate;
    @Autowired
    public FeiZhiTongServiceImpl(FztApiProperties apiProperties){
        this.apiProperties = apiProperties;
    }

    public String http(GatherLog gatherLog, Map<String,String> params,String organCode){
        String secretKey = WarehouseCache.organSecretKeys.get(organCode);
        String url = apiProperties.getDomain()+"/rsdc/api/"+gatherLog.getGatherType()+"/"+apiProperties.getVersion()+"/"+secretKey;
        String queryParams ="";
        if(params!=null){
            for(String key : params.keySet()){
                if(StringUtils.isEmpty(queryParams)){
                    queryParams +="?"+key+"="+params.get(key);
                }else {
                    queryParams += "&" + key + "=" + params.get(key);
                }
            }
        }
        url += queryParams;
        gatherLog.setGatherUrl(url);
        gatherLog.setGatherParams(queryParams);
        gatherLog.setCreateTime(new Date());
        gatherLog.setCreateDate(new Date());
        logger.info("===废纸通API请求地址【{}】===START===",url);
        String json = HttpUtil.getMain(url);
        logger.info("===废纸通API请求地址【{}】===END===",url);
        return json;
    }

    /**
     * 获取货品列表
     * @return
     */
    public List<FztProductInfo> getProducts() {
        GatherLog gatherLog = new GatherLog();
        gatherLog.setGatherType(GatherType.PRODUCT);
        Map<String, String> params = new HashMap<>();
        String json = http(gatherLog, params,"1");
        ApiResult result = JSON.parseObject(json, ApiResult.class);
        if ("200".equals(result.getStatus())) {
            return result.parse(FztProductInfo.class);
        } else {
            logger.error("===请求异常【{}】", result.getMessage());
        }
        kafkaTemplate.send("gatherLog-save", GatherType.PRODUCT, JSON.toJSONString(gatherLog));
        return null;
    }

    /**
     * 获取供应商列表
     * @param organCode
     * @param icno
     * @return
     */
    public List<FztSupplierInfo> getSuppliers(String organCode, String icno) {
        GatherLog gatherLog = new GatherLog();
        gatherLog.setGatherType(GatherType.SUPPLIER);
        // 参数
        Map<String, String> params = new HashMap<>();
        params.put("organCode", organCode);
        if (!StringUtils.isEmpty(icno)) {
            params.put("icno", icno);
        }
        String json = http(gatherLog, params,organCode);
        ApiResult result = JSON.parseObject(json, ApiResult.class);
        if ("200".equals(result.getStatus())) {
            return result.parse(FztSupplierInfo.class);
        } else {
            logger.error("===请求异常【{}】", result.getMessage());
        }
        kafkaTemplate.send("gatherLog-save", GatherType.SUPPLIER, JSON.toJSONString(gatherLog));
        return null;
    }

    /**
     * 获取订单
     * @param start 开始日期
     * @param end 截止日期
     * @param organCode 仓库代码
     * @param orderNo 指定单号
     * @param supplierNo 指定供应商代码
     * @param lastOrderNo 指定上次最后一条记录
     * @return
     */
    public PageOrder<FztPurOrder> getPurOrders(String start, String end, String organCode, String orderNo, String supplierNo, String lastOrderNo){
        Map<String,String> queryParams =new HashMap<>();
        if(!StringUtils.isEmpty(start)){
            queryParams.put("tradedayS",start);
        }
        if(!StringUtils.isEmpty(end)){
            queryParams.put("tradedayE",end);
        }
        if(!StringUtils.isEmpty(organCode)){
            queryParams.put("organCode",organCode);
        }
        if(!StringUtils.isEmpty(orderNo)){
            queryParams.put("bno",orderNo);
        }
        if(!StringUtils.isEmpty(supplierNo)){
            queryParams.put("icno",supplierNo);
        }
        if(!StringUtils.isEmpty(lastOrderNo)){
            queryParams.put("lastNo",lastOrderNo);
        }
        queryParams.put("status","4");
        GatherLog gatherLog = new GatherLog();
        gatherLog.setGatherType(GatherType.PUR_ORDER);
        gatherLog.setGatherParams(JSON.toJSONString(queryParams));
        gatherLog.setLastId(lastOrderNo);
        String json = http(gatherLog, queryParams,organCode);
        ApiResult result = JSON.parseObject(json, ApiResult.class);
        if ("200".equals(result.getStatus())) {
            PageOrder<FztPurOrder> page =new PageOrder<>();
            int total = result.getResult().getIntValue("total");
            int last = result.getResult().getIntValue("left");
            String newLastOrderNo =result.getResult().getString("lastNo");
            page.setTotal(total);
            page.setLeft(last);
            page.setLastNo(newLastOrderNo);
            if(page.getTotal()>0) {
                page.setList(result.parse(FztPurOrder.class));
            }else{
                page.setList(new ArrayList<>());
            }
            gatherLog.setCount(total);
            // kafkaTemplate.send("gatherLog-save", GatherType.SUPPLIER, JSON.toJSONString(gatherLog));
            return page;
        } else {
            logger.error("===请求异常【{}】", result.getMessage());
        }
        return null;
    }

}
